package spikes.keyboard;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Observable;
import java.util.Scanner;

import javax.swing.JFrame;

public class NarwhalKeyboard extends Observable {

	private JFrame frame;
	private boolean caps;
	private boolean shift;
	private StringBuilder sb;
	
	public NarwhalKeyboard() {
		sb = new StringBuilder();
		
		frame = new JFrame();
		frame.setSize(800, 400);
		frame.setLocation(100, 50);
		frame.setUndecorated(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setAlwaysOnTop(true);
		frame.setLayout(null);

		loadKeys();
		frame.setVisible(true);
	}

	private void loadKeys() {
		Scanner s = null;
		try {
			s = new Scanner(new File("keyboard"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return;
		}

		while (s.hasNext()) {
			int size = 55;
			int xOffset = (frame.getBounds().width - 14*size)/2;
			int yOffset = frame.getBounds().height- 5*size- 20;
			String c = s.next();
			String c2 = s.next();
			int x = (int) (s.nextDouble() * size) + xOffset;
			int y = (int) (s.nextDouble() * size) + yOffset; 
			int width = (int) (s.nextDouble() * size);
			int height = (int) (s.nextDouble() * size);
			Key k = null;
			
			if (c.equals("{}")) {
				if (c2.equals("ENTER")) {
					k = new EnterKey(this, "Enter");
				} else if (c2.equals("SPACE")) {
					k = new SpaceKey(this, "Space");
				} else if (c2.equals("BACKSPACE")) {
					k = new BackspaceKey(this, "<--");
				} else if(c2.equals("TAB")) {
					k = new TabKey(this, "TAB");
				} else if(c2.equals("CAPS")) {
					k = new CapsKey(this,"Caps Lock");
				} else if (c2.equals("SHIFT")) {
					k = new ShiftKey(this, "Shift");
				} else {
					k = new Key(this,c,c2);
				} 
			} else {
				k = new Key(this,c,c2);				
			}
			
			
			addObserver(k);
			k.setBounds(x, y, width, height);
			frame.add(k);
		}
	}

	public boolean isCaps() {
		return caps || shift;
	}
	
	public void backspace() {
		if (sb.length() != 0)
			sb.deleteCharAt(sb.length()-1);
	}
	
	public void enter() {
		System.out.println(sb.toString());
	}
	
	public void pressKey(String key) {
		sb.append(key);
		if (shift = true) {
			shift = false;
			setChanged();
			notifyObservers();
		}
		
	}
	
	public void toggleCaps() {
		caps = !caps;
		shift = false;
		setChanged();
		notifyObservers();
	}
	
	public void tab() {
		
	}
	
	public void toggleShift() {
		shift = !shift;
		setChanged();
		notifyObservers();
	}
	
}